package cn.zzm.support.activeMQ;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Component;

import javax.jms.*;
import java.util.UUID;

/**
 * @program: study
 * @description:模拟springMVC方式（非springboot方式） 实现request-response模式
 * @author: 周昭名
 * @create: 2019-04-10 19:35
 **/
@Component
public class JmsQueueRespProduser {

    @Autowired
    @Qualifier("jmsQueueTemplate")
    private JmsTemplate jmsTemplate;
    @Autowired
    private QueueRespListener queueResponseListener;


    public void send(String queueName,String msgStr){

        String uuid = UUID.randomUUID().toString();
        try {
        Session session = jmsTemplate.getConnectionFactory().createConnection().createSession(false,0);
        Destination tempDestinateion = session.createTemporaryQueue();

        jmsTemplate.send(queueName, new MessageCreator() {
            @Override
            public Message createMessage(Session session) throws JMSException {
                Message msg = session.createTextMessage(msgStr);
                //设置消费者应答消息
                MessageConsumer responseConsumer = session.createConsumer(tempDestinateion);
                responseConsumer.setMessageListener(queueResponseListener);
                msg.setJMSReplyTo(tempDestinateion);
                msg.setJMSCorrelationID(uuid);
                return msg;
            }
        });

        MessageConsumer replyConsumer = session.createConsumer("responseQueueTest","JMSCorrelationID='" + uuid + "'");
        replyConsumer.setMessageListener(new MessageListener() {
            public void onMessage(Message m) {
                try {
                    System.out.println("JmsQueueRespProduser" + " get reply:" + ((TextMessage) m).getText());
                } catch (JMSException e) {
                }
            }
        });
    } catch (JMSException e) {
        e.printStackTrace();
    }
    }


}

